/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.security;

import han.bashe.business.pipeline.Handler;
import han.bashe.business.pipeline.PipelineContext;
import han.bashe.common.entity.BifangEntityConstants;
import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.schema.MappingServiceInfoWrapper;
import han.bashe.common.schema.ServiceInfoWrapper;

import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class SecurityHandler extends Handler{
	
	private static Log logger = LogFactory.getLog(SecurityHandler.class);
	
	private SecurityController controller = SecurityControllerFactory.getSecurityController();

	@Override
	public void postProcess(PipelineContext ctx) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preProcess(PipelineContext ctx) {
		if (ctx.hasError())
			return false;
		if(ctx.isLocalDomainService()){
			ServiceInfoWrapper s = ctx.getService();
			HashMap<String,String> qos = s.getServiceQos();
			if(qos.get(BifangEntityConstants.QOS_ACL).equals(BifangEntityConstants.QOS_NO)){
				return false;
			}
			return true;
		}else{
			MappingServiceInfoWrapper s = ctx.getMappingService();
			HashMap<String,String> qos = s.getServiceQos();
			if(qos.get(BifangEntityConstants.QOS_ACL).equals(BifangEntityConstants.QOS_NO)){
				return false;
			}
			return true;
		}
		
	}

	@Override
	public void process(PipelineContext ctx) {
		logger.info("SecurityHandler process......");
		try {
			boolean ret = controller.canAccess(ctx.getRequest());
			if(! ret){
				throw new BasheException(BasheErrorCode.SECURITY_ERROR,"user password invalid or user has no permission to access service");
			}
		} catch (Exception e) {
		
			logger.error("SecurityHandler.process() error",e);
			ctx.setError(e);
		
		}
		
	}

}
